package com.ayuku.retail.ui.pembelian;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.nebula.widgets.grid.Grid;
import org.eclipse.nebula.widgets.grid.GridColumn;
import org.eclipse.nebula.widgets.grid.GridItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;

import com.ayuku.commons.AYConst;
import com.ayuku.commons.AyBigDecimal;
import com.ayuku.commons.AyDate;
import com.ayuku.commons.AyInteger;
import com.ayuku.commons.AyukuDB;
import com.ayuku.commons.Util;
import com.ayuku.retail.business.purchase.PurchaseImpl;
import com.ayuku.retail.persistence.model.ItemPurchase;
import com.ayuku.retail.persistence.model.Purchase;
import com.ayuku.retail.persistence.model.TrxTempSale;
import com.ayuku.retail.ui.supplier.FormSupplier;
import com.ayuku.retail.ui.supplier.SupplierLookup;

/**
 * 
 * @author putu kusuma <putukn@gmail.com>
 *
 */
public class FrmPurchase extends org.eclipse.swt.widgets.Dialog {
	private int formMode = AYConst.MODE_VIEW;
	private Label label1;
	private Text txtNote;
	private String formKey = null;

	public int getFormMode() {
		return formMode;
	}

	public void setFormMode(int formMode) {
		this.formMode = formMode;
	}

	public String getFormKey() {
		return formKey;
	}

	public void setFormKey(String formKey) {
		this.formKey = formKey;
	}

	private Shell dialogShell;
	private Grid tableData;
	private GridColumn clmCode;
	private AyBigDecimal txtDisct;
	private AyBigDecimal txtGrandTotal;
	private AyBigDecimal txtDiscAmount;
	private Label label9;
	private AyBigDecimal txtSubTotal;
	private Label label7;
	private Composite composite4;
	private Text txtSupplier;
	private AyDate txtDate;
	private Label label8;
	private Label label6;
	public Text txtTrxNo;
	private Label label5;
	private Composite composite1;
	private Composite composite3;
	private Composite composite2;
	private Label label3;
	private GridColumn clmTotal;
	private GridColumn clmDisc;
	private GridColumn clmQty;
	private GridColumn clmHarga;
	private GridColumn clmKeterangan;
	private String funcId;
	private Button btnSave;

	private Button btnAdd;
	private Label lblTermin;
	private AyInteger txtTermint;
	private Combo cmbPembayaran;
	private Label label4;
	private Label label2;
	private Button btnLookup;
	private Text txtSupplierName;
	private Button btnBrowse;
	private Button btnClose;
	private Button button5;
	private Button button4;

	public String getFuncId() {
		return funcId;
	}

	public void setFuncId(String funcId) {
		this.funcId = funcId;
	}

	public FrmPurchase(Shell parent, int style, final int mode) {
		super(parent, style);
		this.formMode = mode;
	}

	public void open() {
		try {

			Shell parent = getParent();
			dialogShell = new Shell(parent, SWT.SHELL_TRIM);
	
			FormLayout thisLayout = new FormLayout();
			dialogShell.setBackground(SWTResourceManager
					.getColor(153, 204, 255));

		
			dialogShell.setText("Transaksi Pembelian");

			composite1 = new Composite(dialogShell, SWT.NONE);
			composite1.setLayout(new GridLayout(2, false));
			FormData composite1LData = new FormData();
			composite1LData.top = new FormAttachment(1000, 1000, -42);
			composite1LData.left = new FormAttachment(0, 1000, 0);
			composite1LData.width = 1011;
			composite1LData.right = new FormAttachment(1000, 1000, 0);
			composite1LData.bottom = new FormAttachment(1000, 1000, 0);
			composite1.setLayoutData(composite1LData);

			btnSave = new Button(composite1, SWT.PUSH | SWT.CENTER);
			GridData gd_btnSave = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
			gd_btnSave.widthHint = 89;
			btnSave.setLayoutData(gd_btnSave);
			btnSave.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			btnSave.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent arg0) {

					saveData();

				}
			});
			btnSave.setText("&Save  [F8]");

			btnClose = new Button(composite1, SWT.PUSH | SWT.CENTER);
			btnClose.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent arg0) {
					dialogShell.dispose();
				}
			});
			GridData gd_btnClose = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
			gd_btnClose.widthHint = 81;
			btnClose.setLayoutData(gd_btnClose);
			btnClose.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					//keyDsetect(arg0);
					dialogShell.dispose();
				}
			});
			btnClose.setText("&Exit");

			dialogShell.addKeyListener(new KeyAdapter() {
				public void keyPressed(KeyEvent evt) {
					dialogShellKeyPressed(evt);
				}
			});

			composite4 = new Composite(dialogShell, SWT.NONE);
			composite4.setLayout(null);
			FormData composite4LData = new FormData();
			composite4LData.right = new FormAttachment(composite1, 0, SWT.RIGHT);
			composite4LData.width = 453;
			composite4.setLayoutData(composite4LData);
			composite4
					.setBackground(SWTResourceManager.getColor(153, 204, 255));

			label3 = new Label(composite4, SWT.NONE);
			label3.setBounds(75, 36, 174, 22);
			label3.setText("Discount Rp. :");
			label3.setFont(com.swtdesigner.SWTResourceManager.getFont("Arial",
					12, SWT.BOLD));
			label3.setAlignment(SWT.RIGHT);
			label3.setBackground(SWTResourceManager.getColor(153, 204, 255));

			label7 = new Label(composite4, SWT.NONE);
			label7.setBounds(75, 10, 174, 22);
			label7.setText("Sub Total  Rp. :");
			label7.setAlignment(SWT.RIGHT);
			label7.setFont(com.swtdesigner.SWTResourceManager.getFont("Arial",
					12, SWT.BOLD));
			label7.setBackground(SWTResourceManager.getColor(153, 204, 255));

			txtSubTotal = new AyBigDecimal(composite4, SWT.BORDER);
			txtSubTotal.setEnabled(false);
			txtSubTotal.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});

			txtSubTotal.getOrgComponent().getControl().addVerifyListener(
					new VerifyListener() {
						public void verifyText(VerifyEvent evt) {
							subTotalChanged(evt);
						}
					});

			txtSubTotal.setBounds(255, 11, 188, 22);
			txtSubTotal.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.BOLD));

			label9 = new Label(composite4, SWT.NONE);
			label9.setBounds(75, 63, 174, 22);
			label9.setText("Grand Total Rp. :");
			label9.setAlignment(SWT.RIGHT);
			label9.setFont(com.swtdesigner.SWTResourceManager.getFont("Arial",
					12, SWT.BOLD));
			label9.setBackground(SWTResourceManager.getColor(153, 204, 255));

			txtDiscAmount = new AyBigDecimal(composite4, SWT.BORDER);
			txtDiscAmount.setEnabled(false);
			txtDiscAmount.getOrgComponent().getControl().addFocusListener(
					new FocusAdapter() {
						@Override
						public void focusGained(FocusEvent arg0) {
							txtDiscAmount.getOrgComponent().getControl()
									.selectAll();
						}
					});
			txtDiscAmount.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
		
						keyDetect(arg0);
					
				}

			});

			
			
			txtDiscAmount.setBounds(320, 36, 123, 22);
			txtDiscAmount.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.BOLD));

			txtGrandTotal = new AyBigDecimal(composite4, SWT.BORDER);
			txtGrandTotal.setEnabled(false);
			txtGrandTotal.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			txtGrandTotal.setBounds(255, 63, 188, 22);
			txtGrandTotal.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.BOLD));

			txtDisct = new AyBigDecimal(composite4, SWT.BORDER);
			txtDisct.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}

				@Override
				public void keyReleased(KeyEvent arg0) {
					txtDisctKeyReleased(arg0);
				}
			});
			txtDisct.setBounds(255, 36, 40, 22);
			txtDisct.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.BOLD));
			txtDisct.setStringFormatter("#0");

			label2 = new Label(composite4, SWT.NONE);
			label2.setBounds(300, 38, 13, 22);
			label2.setText("%    ");
			label2.setBackground(SWTResourceManager.getColor(153, 204, 255));

			txtDisct.getOrgComponent().getControl().addFocusListener(
					new FocusAdapter() {
						public void focusGained(FocusEvent evt) {
							txtDisctFocusGained(evt);
						}
					});

			tableData = new Grid(dialogShell, SWT.BORDER | SWT.H_SCROLL
					| SWT.V_SCROLL);
			tableData.setForeground(com.swtdesigner.SWTResourceManager
					.getColor(SWT.COLOR_BLUE));
			composite4LData.bottom = new FormAttachment(tableData, 145,
					SWT.BOTTOM);
			composite4LData.top = new FormAttachment(tableData, 6);
			tableData.setCellSelectionEnabled(true);
			tableData.setAutoHeight(true);
			tableData.setLinesVisible(true);
			tableData.setHeaderVisible(true);
			tableData.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 12, SWT.NORMAL));
			tableData.setItemHeight(18);

			clmCode = new GridColumn(tableData, SWT.NONE);
			clmCode.setText("KODE");
			clmCode.setResizeable(true);
			clmCode.setWidth(180);

			clmKeterangan = new GridColumn(tableData, SWT.NONE);
			clmKeterangan.setText("KETERANGAN");
			clmKeterangan.setResizeable(true);
			clmKeterangan.setWidth(360);

			clmHarga = new GridColumn(tableData, SWT.NONE);
			clmHarga.setText("HARGA");
			clmHarga.setResizeable(true);
			clmHarga.setWidth(150);
			clmHarga.setAlignment(SWT.RIGHT);

			clmQty = new GridColumn(tableData, SWT.NONE);
			clmQty.setText("QTY");
			clmQty.setResizeable(true);
			clmQty.setWidth(60);
			clmQty.setAlignment(SWT.RIGHT);

			clmDisc = new GridColumn(tableData, SWT.NONE);
			clmDisc.setText("DISC.(%)");
			clmDisc.setResizeable(true);
			clmDisc.setWidth(80);
			clmDisc.setAlignment(SWT.RIGHT);

			clmTotal = new GridColumn(tableData, SWT.NONE);
			clmTotal.setText("TOTAL");
			clmTotal.setResizeable(true);
			clmTotal.setWidth(150);
			clmTotal.setAlignment(SWT.RIGHT);

			composite2 = new Composite(dialogShell, SWT.NONE);
			composite2.setForeground(com.swtdesigner.SWTResourceManager
					.getColor(SWT.COLOR_TITLE_BACKGROUND));
			composite2.setLayout(new GridLayout(2, false));
			FormData composite2LData = new FormData();
			composite2LData.top = new FormAttachment(0);
			composite2LData.width = 1019;
			composite2LData.height = 106;
			composite2LData.left = new FormAttachment(0, 1000, 0);
			composite2LData.right = new FormAttachment(1000, 1000, 0);
			composite2.setLayoutData(composite2LData);
			composite2
					.setBackground(SWTResourceManager.getColor(153, 204, 255));

		

			composite3 = new Composite(composite2, SWT.NONE);
			GridData gd_composite3 = new GridData(SWT.LEFT, SWT.CENTER, false,
					false, 1, 1);
			gd_composite3.widthHint = 574;
			composite3.setLayoutData(gd_composite3);

			composite3.setLayout(null);
			composite3
					.setBackground(SWTResourceManager.getColor(153, 204, 255));

			label5 = new Label(composite3, SWT.NONE);
			label5.setText("No. Transaksi:");
			label5.setFont(com.swtdesigner.SWTResourceManager.getFont("Arial",
					12, SWT.NORMAL));
			label5.setAlignment(SWT.RIGHT);
			label5.setBackground(SWTResourceManager.getColor(153, 204, 255));
			label5.setBounds(7, 10, 108, 22);

			txtTrxNo = new Text(composite3, SWT.BORDER);
			txtTrxNo.setForeground(com.swtdesigner.SWTResourceManager
					.getColor(SWT.COLOR_TITLE_BACKGROUND));
			txtTrxNo.setEnabled(false);
			txtTrxNo.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			txtTrxNo.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.NORMAL));
			txtTrxNo.setBounds(121, 10, 116, 22);

			label6 = new Label(composite3, SWT.NONE);
			label6.setText("Tanggal:");
			label6.setFont(com.swtdesigner.SWTResourceManager.getFont("Arial",
					12, SWT.NORMAL));
			label6.setAlignment(SWT.RIGHT);
			label6.setBackground(SWTResourceManager.getColor(153, 204, 255));
			label6.setBounds(7, 36, 108, 22);

			label8 = new Label(composite3, SWT.NONE);
			label8.setText("Supplier:");
			label8.setFont(com.swtdesigner.SWTResourceManager.getFont("Arial",
					12, SWT.NORMAL));
			label8.setAlignment(SWT.RIGHT);
			label8.setBackground(SWTResourceManager.getColor(153, 204, 255));
			label8.setBounds(7, 62, 108, 22);

			txtDate = new AyDate(composite3, SWT.MEDIUM | SWT.DROP_DOWN
					| SWT.BORDER);
			txtDate.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			txtDate.setFont(com.swtdesigner.SWTResourceManager.getFont("Arial",
					11, SWT.NORMAL));
			txtDate.setBounds(121, 36, 116, 20);

			txtSupplier = new Text(composite3, SWT.BORDER);
			txtSupplier.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseDoubleClick(MouseEvent arg0) {
					showLookupSupplier();
				}
			});
			txtSupplier.setBackground(com.swtdesigner.SWTResourceManager
					.getColor(SWT.COLOR_YELLOW));
			txtSupplier.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.keyCode == SWT.CR) {
						showLookupSupplier();
					} else {
						keyDetect(arg0);
					}
				}
			});
			txtSupplier.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.NORMAL));
			txtSupplier.setBounds(121, 60, 116, 23);

			btnBrowse = new Button(composite3, SWT.PUSH | SWT.CENTER);
			btnBrowse.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 8, SWT.NORMAL));
			btnBrowse.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent evt) {
					if (evt.keyCode != SWT.CR) {
						showFormSupplier();
					} else {
						keyDetect(evt);
					}
				}
			});
			btnBrowse.setText(" New ");
			btnBrowse.setBackground(SWTResourceManager.getColor(153, 204, 255));
			btnBrowse.setBounds(504, 59, 39, 24);
			btnBrowse.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					showFormSupplier();
				}
			});

			txtSupplierName = new Text(composite3, SWT.BORDER);

			txtSupplierName.setBackground(com.swtdesigner.SWTResourceManager
					.getColor(255, 255, 255));
			txtSupplierName.setEnabled(false);
			txtSupplierName.setEditable(false);
			txtSupplierName.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			txtSupplierName.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.NORMAL));
			txtSupplierName.setBounds(239, 60, 230, 23);

			btnLookup = new Button(composite3, SWT.PUSH | SWT.CENTER);
			btnLookup.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 8, SWT.NORMAL));
			btnLookup.setText("...");
			btnLookup.setBackground(SWTResourceManager.getColor(153, 204, 255));
			btnLookup.setBounds(475, 60, 25, 24);

			label4 = new Label(composite3, SWT.NONE);
			label4.setFont(com.swtdesigner.SWTResourceManager.getFont("Tahoma",
					12, SWT.NORMAL));
			label4.setText("Cash/Credit:");
			label4.setAlignment(SWT.RIGHT);
			label4.setBackground(SWTResourceManager.getColor(153, 204, 255));
			label4.setBounds(240, 12, 106, 18);

			cmbPembayaran = new Combo(composite3, SWT.NONE);
			cmbPembayaran.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent arg0) {
					changeTermint();
				}
			});
			cmbPembayaran.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.NORMAL));
			cmbPembayaran.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			cmbPembayaran.setItems(new String[] { "Cash", "1 Minggu",
					"2 Minggu", "3 Minggu", "4 Minggu", "Custom" });
			cmbPembayaran.setBounds(349, 10, 126, 25);

			txtTermint = new AyInteger(composite3, SWT.BORDER);
			txtTermint.getOrgComponent().getControl().setTextLimit(3);
			txtTermint.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			txtTermint.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.NORMAL));

			txtTermint.setBounds(479, 10, 47, 25);

			lblTermin = new Label(txtTermint, SWT.NONE);
			lblTermin.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Tahoma", 12, SWT.NORMAL));
			lblTermin.setText("Hari");
			lblTermin.setBackground(SWTResourceManager.getColor(153, 204, 255));

			Label label = new Label(composite2, SWT.NONE);
			label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false,
					1, 1));

			btnLookup.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					showLookupSupplier();
				}
			});
			btnLookup.addKeyListener(new KeyAdapter() {
				public void keyPressed(KeyEvent evt) {
					btnLookupKeyPressed(evt);
				}
			});

			FormData table1LData = new FormData();
			table1LData.width = 1005;
			table1LData.height = 184;
			table1LData.top = new FormAttachment(0, 1000, 110);
			table1LData.bottom = new FormAttachment(1000, 1000, -192);
			table1LData.right = new FormAttachment(1000, 1000, -2);
			table1LData.left = new FormAttachment(0, 1000, 4);
			tableData.setItemCount(0);

			tableData.setLayoutData(table1LData);
			tableData.addMouseListener(new MouseAdapter() {
				public void mouseDoubleClick(MouseEvent evt) {
					tableDataMouseDoubleClick(evt);
				}
			});
			tableData.addKeyListener(new KeyAdapter() {
				public void keyPressed(KeyEvent evt) {

					if (evt.keyCode == SWT.CR) {
						InputPembelian p = new InputPembelian(dialogShell,
								SWT.NONE, tableData, txtSubTotal);
						p.open();
					} else {
						keyDetect(evt);
					}
				}
			});
			tableData.addControlListener(new ControlAdapter() {
				public void controlResized(ControlEvent evt) {
					tableDataControlResized(evt);
				}
			});
		

			txtSubTotal.getOrgComponent().getControl().setEditable(false);

			txtGrandTotal.getOrgComponent().getControl().setEditable(false);
			dialogShell.addListener(SWT.Traverse, new Listener() {
				public void handleEvent(Event e) {
					if (e.detail == SWT.TRAVERSE_ESCAPE) {
						e.doit = false;
					}
				}
			});
			dialogShell.addListener(SWT.Close, new Listener() {
				public void handleEvent(Event event) {
					int style = SWT.APPLICATION_MODAL | SWT.YES | SWT.NO;
					MessageBox messageBox = new MessageBox(dialogShell, style);
					messageBox.setText("Information");
					messageBox.setMessage("Tutup Transaksi Pembelian?");
					event.doit = messageBox.open() == SWT.YES;
				}
			});

			tableData.setItemCount(25);

			Composite composite = new Composite(dialogShell, SWT.NONE);
			FormData fd_composite = new FormData();
			fd_composite.bottom = new FormAttachment(composite1, -6);
			fd_composite.top = new FormAttachment(tableData, 6);
			fd_composite.right = new FormAttachment(composite4, -206);
			fd_composite.left = new FormAttachment(0, 5);

			lblBayarRp = new Label(composite4, SWT.NONE);
			lblBayarRp.setText("Bayar Rp. :");
			lblBayarRp.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 12, SWT.BOLD));
			lblBayarRp.setBackground(com.swtdesigner.SWTResourceManager
					.getColor(153, 204, 255));
			lblBayarRp.setAlignment(SWT.RIGHT);
			lblBayarRp.setBounds(75, 88, 174, 22);

			txtBayar = new AyBigDecimal(composite4, SWT.BORDER);
			txtBayar.getOrgComponent().getControl().addFocusListener(new FocusAdapter() {
				@Override
				public void focusGained(FocusEvent arg0) {					
					txtBayar.setBackground(com.swtdesigner.SWTResourceManager
							.getColor(SWT.COLOR_YELLOW));
				}
				@Override
				public void focusLost(FocusEvent arg0) {
					txtBayar.setBackground(com.swtdesigner.SWTResourceManager
							.getColor(SWT.COLOR_WHITE));
				}
			});
			txtBayar.getOrgComponent().getControl().addFocusListener(
					new FocusAdapter() {
						@Override
						public void focusGained(FocusEvent arg0) {
							txtBayar.getOrgComponent().getControl().selectAll();
						}
					});
			txtBayar.addKeyListener(new KeyAdapter() {

				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}

				@Override
				public void keyReleased(KeyEvent arg0) {
					calculateTunggakan();
				}
			});
			txtBayar.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.BOLD));
			txtBayar.setBounds(255, 89, 188, 22);

			lblTunggakanRp = new Label(composite4, SWT.NONE);
			lblTunggakanRp.setText("Tunggakan Rp. :");
			lblTunggakanRp.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 12, SWT.BOLD));
			lblTunggakanRp.setBackground(com.swtdesigner.SWTResourceManager
					.getColor(153, 204, 255));
			lblTunggakanRp.setAlignment(SWT.RIGHT);
			lblTunggakanRp.setBounds(75, 113, 174, 22);

			txtTunggakan = new AyBigDecimal(composite4, SWT.BORDER);
			txtTunggakan.setEnabled(false);
			txtTunggakan.setFont(com.swtdesigner.SWTResourceManager.getFont(
					"Arial", 11, SWT.BOLD));
			txtTunggakan.setBounds(255, 115, 188, 22);
			composite.setLayoutData(fd_composite);
			composite.setBackground(SWTResourceManager.getColor(153, 204, 255));
			composite.setLayout(null);

			txtNote = new Text(composite, SWT.BORDER | SWT.WRAP | SWT.MULTI);
			txtNote.setBounds(5, 53, 400, 72);

			label1 = new Label(composite, SWT.RIGHT);
			label1.setBounds(8, 35, 31, 16);
			label1.setText("Note:");
			label1.setAlignment(SWT.RIGHT);
			label1.setBackground(SWTResourceManager.getColor(153, 204, 255));
			label1.setFont(com.swtdesigner.SWTResourceManager.getFont("Arial",
					10, SWT.NORMAL));

			btnAdd = new Button(composite, SWT.BORDER | SWT.FLAT | SWT.CENTER);
			btnAdd.setForeground(com.swtdesigner.SWTResourceManager
					.getColor(SWT.COLOR_BLUE));
			btnAdd.setBounds(3, 2, 110, 26);
			btnAdd.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent arg0) {
					showInputItem();
				}
			});
			btnAdd.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			btnAdd.setText("  Tambah Item [F5]  ");

			button4 = new Button(composite, SWT.BORDER | SWT.FLAT | SWT.CENTER);
			button4.setForeground(com.swtdesigner.SWTResourceManager
					.getColor(SWT.COLOR_BLUE));
			button4.setBounds(117, 2, 110, 26);
			button4.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent arg0) {
					doEditdata();
				}
			});
			button4.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			button4.setText("Edit Item [F2]");

			button5 = new Button(composite, SWT.BORDER | SWT.FLAT | SWT.CENTER);
			button5.setForeground(com.swtdesigner.SWTResourceManager
					.getColor(SWT.COLOR_BLUE));
			button5.setBounds(231, 2, 110, 26);
			button5.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent arg0) {
					doDeleteItem();
				}
			});
			button5.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			button5.setText("    Hapus Item [F4]     ");
			txtNote.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					keyDetect(arg0);
				}
			});
			dialogShell.open();
			dialogShell.setLayout(thisLayout);
			dialogShell.setSize(1087, 531);
			dialogShell.layout();
			dialogShell.setMaximized(true);
			
			startNewTrx();

			Display display = dialogShell.getDisplay();
			while (!dialogShell.isDisposed()) {
				if (!display.readAndDispatch())
					display.sleep();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*private void hitungGrandTotalAfterDiscAmountChanged() {
		txtDisct.setValue(BigDecimal.valueOf(0));
		BigDecimal grandTotal = txtSubTotal.getValue().subtract(
				txtDiscAmount.getValue());
		txtGrandTotal.setValue(grandTotal);
	}*/

	protected void showInputItem() {
		InputPembelian p = new InputPembelian(dialogShell, SWT.NONE, tableData,
				txtSubTotal);
		p.open();
		doFocusOnTable();
	}

	protected void calculateTunggakan() {

		
		BigDecimal tunggakan = txtBayar.getValue().subtract(txtGrandTotal.getValue());

		txtTunggakan.setValue(tunggakan);

	}

	protected void changeTermint() {
		String cmbText = cmbPembayaran.getText().trim();
		txtTermint.setVisible(true);
		lblTermin.setVisible(true);
		if (cmbText.equalsIgnoreCase("Cash")) {
			txtTermint.setValue(0);
			txtTermint.setVisible(false);
			lblTermin.setVisible(false);
		} else if (cmbText.equalsIgnoreCase("Custom")) {
			txtTermint.setValue(1);
		} else if (cmbText.equalsIgnoreCase("1 Minggu")) {
			txtTermint.setValue(7);
		} else if (cmbText.equalsIgnoreCase("2 Minggu")) {
			txtTermint.setValue(14);
		} else if (cmbText.equalsIgnoreCase("3 Minggu")) {
			txtTermint.setValue(21);
		} else if (cmbText.equalsIgnoreCase("4 Minggu")) {
			txtTermint.setValue(28);
		} else {
			txtTermint.setValue(30);
		}

	}

	protected void keyDetect(KeyEvent evt) {
		if (evt.keyCode == SWT.F2) {
			doEditdata();
			return;
		} else if (evt.keyCode == SWT.F4) {
			doDeleteItem();
			return;
		} else if (evt.keyCode == SWT.F8) {
			saveData();
			return;
		} else if (evt.keyCode == SWT.F5) {
			showInputItem();
			return;
		}else if (evt.keyCode == SWT.END) {
			txtBayar.setFocus();
			return;
		}

	}

	protected void saveData() {
		if (doValidate()) {
			Purchase obj = new Purchase();
			obj.setTrxCode(txtTrxNo.getText());
			obj.setSupplier(txtSupplier.getText());
			obj.setDiscount(txtDiscAmount.getValue());
			obj.setGrandTotal(txtGrandTotal.getValue());
			obj.setTrxDate(txtDate.getValue());
			obj.setBayar(txtBayar.getValue());
			obj.setHutang(txtTunggakan.getValue());

			if (cmbPembayaran.getText().equalsIgnoreCase("Cash")) {
				obj.setIsLunas("1");
				obj.setTermint(0);
			} else {
				obj.setIsLunas("0");
				obj.setTermint(txtTermint.getValue());
			}

			obj.setOperator(Util.getCurrentUser().getName());
			obj.setOperator(Util.getCurrentUser().getName());
			obj.setSubTotal(txtSubTotal.getValue());
			obj.setGrandTotal(txtGrandTotal.getValue());
			obj.setCreatedBy(Util.getCurrentUser().getName());
			obj.setCreatedDate(Util.getCurrentDate());
			obj.setModifiedBy(Util.getCurrentUser().getName());
			obj.setModifiedDate(Util.getCurrentDate());
			obj.setNotes(txtNote.getText());

			try {
				Map<String, Object> mp = new HashMap<String, Object>();
				mp.put("hdr", obj);
				mp.put("dtls", getListItem());
				PurchaseImpl.add(mp);
				Util.showMsgBox("Transaksi sudah disimpan!", 1, dialogShell);
				startNewTrx();
			} catch (Exception e) {
				e.printStackTrace();
				Util.showMsgBox("Gagal Insert Data!", 1, dialogShell);
			}
		}
	}

	private void tableDataControlResized(ControlEvent evt) {
		int rect = tableData.getBounds().width;
		int boun = tableData.getBounds().width;
		System.out.println("rect: " + rect);
		System.out.println("boun: " + boun);
		tableData.getColumnCount();

		int total = clmCode.getWidth() + clmHarga.getWidth()
				+ clmQty.getWidth() + clmDisc.getWidth() + clmTotal.getWidth();
		System.out.println("total2" + total);

		clmKeterangan.setWidth(boun - total - 40);

	}

	private void startNewTrx() {

		try {
			AyukuDB.getPersist().executeUpdate("DELETE FROM TRX_TEMP_SALE");
			//AyukuDB.getPersist().executeUpdate("TRUNCATE TABLE TRX_TEMP_SALE");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		String f = AYConst.FOR_TRX_NO_FORMAT.format(cal.getTime());
		txtTrxNo.setText(f);

		txtDate.setValue(cal.getTime());

		tableData.removeAll();
		tableData.clearAll(true);
		tableData.setFocus();
		txtSubTotal.setValue(BigDecimal.valueOf(0));
		txtGrandTotal.setValue(BigDecimal.valueOf(0));
		txtDisct.setValue(BigDecimal.valueOf(0));
		txtDiscAmount.setValue(BigDecimal.valueOf(0));
		cmbPembayaran.setText("Cash");

		txtBayar.setValue(BigDecimal.valueOf(0));
		txtTunggakan.setValue(BigDecimal.valueOf(0));
		txtTermint.setValue(0);
		txtTermint.setVisible(false);
		lblTermin.setVisible(false);

		txtSupplier.setText("");
		txtSupplierName.setText("");
		txtSupplier.setFocus();
	
	}

	Double discPercent = 0.0;
	private Label lblBayarRp;
	private AyBigDecimal txtBayar;
	private Label lblTunggakanRp;
	private AyBigDecimal txtTunggakan;

	private void hitungTotal(Double discPercent) {
		BigDecimal subTot = txtSubTotal.getValue();
		double discAmount = subTot.doubleValue() * discPercent.doubleValue()
				/ 100;
		txtDiscAmount.setValue(BigDecimal.valueOf(discAmount));
		double grandTotal = subTot.doubleValue() - discAmount;
		txtGrandTotal.setValue(BigDecimal.valueOf(grandTotal));

	}

	private void doFocusOnTable() {
		int m = tableData.getItemCount();
		if (m > 0) {
			GridItem itm = tableData.getItem(m - 1);
			tableData.setSelection(m - 1);
			tableData.setFocusItem(itm);
		}
		tableData.setFocus();
	}

	private void doDeleteItem() {
		int i = tableData.getSelectionIndex();

		MessageBox messageBox = new MessageBox(dialogShell, SWT.OK | SWT.CANCEL
				| SWT.ICON_WARNING);
		messageBox
				.setMessage("Anda Yakin akan menghapus data yang anda pilih?");
		if (messageBox.open() == SWT.OK) {
			if (i > -1) {
				GridItem itm = tableData.getItem(i);
				String code = itm.getText(0);
				try {
					AyukuDB.getPersist().executeUpdate(
							"delete from trx_temp_sale where barcode=?", code);
					doReloadList();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

		}
		doFocusOnTable();
	}

	public void doReloadList() throws SQLException {
	/*	List<TrxTempSale> lst = AyukuDB.getPersist().readList(
				TrxTempSale.class, "SELECT * FROM TRX_TEMP_SALE order by idx");
		tableData.removeAll();
		tableData.clearAll(true);
		tableData.setItemCount(lst.size());
		Double tot = 0.0;
		for (int i = 0; i < lst.size(); i++) {

			TrxTempSale sl = lst.get(i);
			tot += sl.getTotal().doubleValue();
			GridItem itm = tableData.getItem(i);
			itm.setText(0, sl.getBarcode());
			itm.setText(1, sl.getKeterangan());
			itm.setText(2, sl.getPrice() + "");
			itm.setText(3, sl.getQty() + "");
			itm.setText(4, sl.getDisc() + "");
			itm.setText(5, sl.getTotal() + "");
			itm.setText(6, sl.getIdx() + "");
		}
		txtSubTotal.setValue(BigDecimal.valueOf(tot));*/

		
		List<TrxTempSale> lst = AyukuDB.getPersist().readList(
				TrxTempSale.class, "SELECT * FROM TRX_TEMP_SALE order by idx");
		tableData.removeAll();
		tableData.clearAll(true);
		tableData.setItemCount(lst.size());
		BigDecimal tot = BigDecimal.valueOf(0);
		for (int i = 0; i < lst.size(); i++) {
			TrxTempSale sl = lst.get(i);

			tot = tot.add(sl.getTotal());

			GridItem itm = tableData.getItem(i);
			itm.setText(0, sl.getBarcode());
			itm.setText(1, sl.getKeterangan());
			itm.setText(2, Util.formatToNumber(sl.getPrice()));
			itm.setText(3, Util.formatToNumber(sl.getQty()));
			itm.setText(4, Util.formatToNumber(sl.getDisc()));
			itm.setText(5, Util.formatToNumber(sl.getTotal()));
			itm.setText(6, sl.getIdx() + "");

		}
		txtSubTotal.setValue(tot);
		//txtCode.setFocus();
	}

	private void doEditdata() {
		/*
		 * Point[] ps = tableData.getCellSelection(); Point p = ps[0];
		 * 
		 * System.out.println("x: " + p.x +", y: "+ p.y);
		 */
		if (tableData.getItemCount() < 1) {
			Util.showMsgBox("Belum ada item", 2, dialogShell);
			return;

		}

		int i = tableData.getSelectionIndex();
		if (i > -1) {
			GridItem itm = tableData.getItem(i);
			String code = new String(itm.getText(0));
			if (code == null || code.trim().equalsIgnoreCase("")) {
				Util.showMsgBox("Kode item kosong, gak bisa diedit!", 2,
						dialogShell);
				return;
			}

			EditItem d = new EditItem(dialogShell, SWT.NULL);
			d.setKode(code);
			d.open();
			try {
				doRecalculateRow(code);
				doReloadList();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			tableData.setFocus();
			tableData.setSelection(i);
			itm = tableData.getItem(i);
			tableData.setFocusItem(itm);

		} else {
			Util.showMsgBox("Silakan pilih item yang akan diedit", 2,
					dialogShell);
			return;
		}

	}

	private void doRecalculateRow(String key) throws SQLException {
		TrxTempSale sold = AyukuDB.getPersist().readByPrimaryKey(
				TrxTempSale.class, key.trim());

		if (sold != null) {
			double totalHarga = sold.getQty().doubleValue()
					* sold.getPrice().doubleValue();
			double totalDiskon = (sold.getDisc().doubleValue() / 100)
					* totalHarga;
			double totalNetto = totalHarga - totalDiskon;
			sold.setTotal(BigDecimal.valueOf(totalNetto));
			AyukuDB.getPersist().update(sold);

		}
	}

	private void tableDataMouseDoubleClick(MouseEvent evt) {
		doEditdata();
	}

	private void dialogShellKeyPressed(KeyEvent evt) {
		InputPembelian p = new InputPembelian(dialogShell, SWT.NONE, tableData,
				txtSubTotal);
		p.open();
	}

	private boolean doValidate() {

		if (getItemNotEmpty() < 1) {
			Util.showMsgBox("Belum ada data barang!", 1, dialogShell);
			tableData.setFocus();

			return false;
		}

		if (txtTrxNo.getText() == null || txtTrxNo.getText().trim() == "") {
			Util.showMsgBox("No Transaksi masih kosong!", 1, dialogShell);
			txtTrxNo.setFocus();

			return false;
		}

		if (txtSupplier.getText() == null || txtSupplier.getText().trim() == "") {
			Util.showMsgBox("Supllier masih kosong!", 1, dialogShell);
			txtSupplier.setFocus();

			return false;
		}
		
		if (txtBayar.getValue().doubleValue()==0) {
			Util.showMsgBox("Kolom bayar masih kosong!", 1, dialogShell);
			txtSupplier.setFocus();

			return false;
		}

		return true;
	}

	private int getItemNotEmpty() {
		int n = tableData.getItemCount();

		int num = 0;
		for (int i = 0; i < n; i++) {
			GridItem itm = tableData.getItem(i);
			if (!itm.getText(0).trim().equals("")) {
				num += 1;
			}
		}
		return num;
	}

	private void txtDisctKeyReleased(KeyEvent evt) {

		// if (evt.keyCode == SWT.CR) {
		double dbl = 0;
		try {
			dbl = txtDisct.getValue().doubleValue();
		} catch (Exception e) {
			dbl = 0;
		}
		hitungTotal(dbl);
		// }
	}

	private void txtDisctFocusGained(FocusEvent evt) {
		txtDisct.getOrgComponent().getControl().selectAll();
	}

	private void subTotalChanged(VerifyEvent evt) {
		txtGrandTotal.setValue(txtSubTotal.getValue().subtract(
				txtDiscAmount.getValue()));
	}

	private void btnLookupKeyPressed(KeyEvent evt) {
		if (evt.keyCode == SWT.CR) {
			showLookupSupplier();
		} else {
			keyDetect(evt);
		}
	}

	private void showLookupSupplier() {
		SupplierLookup lk = new SupplierLookup(getParent(), SWT.NONE) {
			public void setForm(TableItem itm) {
				String code = Util.nullToString(itm.getText(0));
				String name = Util.nullToString(itm.getText(1));
				txtSupplier.setText(code);
				txtSupplierName.setText(name);
			}
		};
		lk.open();

		tableData.setFocus();
		tableData.setSelection(0);
		// tableData.setCellSelection(new Point(0, 0));
	}

	private void showFormSupplier() {
		FormSupplier frm = new FormSupplier(getParent(), SWT.NULL,
				AYConst.MODE_ADD);
		frm.setFuncId(getFuncId());
		frm.open();
		dialogShell.setFocus();
	}

	private List<ItemPurchase> getListItem() throws Exception {
		List<ItemPurchase> lst = new ArrayList<ItemPurchase>();
		GridItem[] itms = tableData.getItems();
		for (int p = 0; p < itms.length; p++) {
			GridItem grdItem = itms[p];
			ItemPurchase item = new ItemPurchase();

			item.setKodeBarang(grdItem.getText(0).trim());
			item.setNamaBarang(grdItem.getText(1).trim());
			item.setHargaBeli(Util.strToBigDecimal(grdItem.getText(2).trim()));
			item.setQty(Util.strToBigDecimal(grdItem.getText(3).trim()));
			item.setDisc(Util.strToBigDecimal(grdItem.getText(4).trim()));
			item.setSubtotal(Util.strToBigDecimal(grdItem.getText(5).trim()));

			System.out.println("Qty: " + Util.strToBigDecimal(grdItem.getText(3).trim()));
			System.out.println("Harga beli: " + Util.strToBigDecimal(grdItem.getText(2).trim()));
			System.out.println("Disc: " +Util.strToBigDecimal(grdItem.getText(4).trim()));
			System.out.println("Subtotal: " + Util.strToBigDecimal(grdItem.getText(5).trim()));
			System.out.println("Satuan: " + item.getSatuan());
			
			
			lst.add(item);
		}
		return lst;
	}
}
